import sys
import requests
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLineEdit, QTextEdit, QLabel, QMessageBox
from PyQt5.QtGui import QIcon, QColor, QFont
import qtawesome as qta

class NoteApp(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Encrypted Notebook")
        self.setWindowIcon(QIcon(qta.icon('fa.lock', color='blue')))
        self.setGeometry(200, 200, 600, 500)

        # 设置背景色
        self.setStyleSheet("background-color: #f4f7fa;")

        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(20, 20, 20, 20)
        self.layout.setSpacing(15)

        # Title Label
        self.title_label = QLabel("Encrypted Notebook")
        self.title_label.setAlignment(Qt.AlignCenter)
        self.title_label.setStyleSheet("font-size: 28px; font-weight: bold; color: #2e2e2e;")
        self.layout.addWidget(self.title_label)

        # URL 输入框
        self.url_input = QLineEdit(self)
        self.url_input.setPlaceholderText("Enter Flask API URL (e.g., http://127.0.0.1:5055) You must add 'http://' in the front of url")
        self.url_input.setStyleSheet("""
            QLineEdit {
                font-size: 14px;
                padding: 10px;
                border-radius: 10px;
                border: 1px solid #ccc;
                background-color: #ffffff;
            }
            QLineEdit:focus {
                border-color: #007bff;
            }
        """)
        self.layout.addWidget(self.url_input)

        # 笔记名称输入框
        self.name_input = QLineEdit(self)
        self.name_input.setPlaceholderText("Enter Note Name")
        self.name_input.setStyleSheet(self.url_input.styleSheet())
        self.layout.addWidget(self.name_input)

        # 密码输入框
        self.password_input = QLineEdit(self)
        self.password_input.setPlaceholderText("Enter Password")
        self.password_input.setEchoMode(QLineEdit.Password)
        self.password_input.setStyleSheet(self.url_input.styleSheet())
        self.layout.addWidget(self.password_input)

        # 笔记内容输入框
        self.content_input = QTextEdit(self)
        self.content_input.setPlaceholderText("Enter Note Content")
        self.content_input.setStyleSheet("""
            QTextEdit {
                font-size: 14px;
                padding: 10px;
                border-radius: 10px;
                border: 1px solid #ccc;
                background-color: #ffffff;
            }
            QTextEdit:focus {
                border-color: #007bff;
            }
        """)
        self.layout.addWidget(self.content_input)

        # 按钮区域
        self.button_layout = QHBoxLayout()
        self.button_layout.setSpacing(20)

        # Create Note Button
        self.create_button = QPushButton(qta.icon('fa.plus', color='white'), "Create Note", self)
        self.create_button.setStyleSheet("""
            QPushButton {
                background-color: #28a745;
                color: white;
                padding: 12px 20px;
                border-radius: 5px;
                font-size: 16px;
                font-weight: bold;
                border: none;
            }
            QPushButton:hover {
                background-color: #218838;
            }
        """)
        self.create_button.clicked.connect(self.create_note)
        self.button_layout.addWidget(self.create_button)

        # Delete Note Button
        self.delete_button = QPushButton(qta.icon('fa.trash', color='white'), "Delete Note", self)
        self.delete_button.setStyleSheet("""
            QPushButton {
                background-color: #dc3545;
                color: white;
                padding: 12px 20px;
                border-radius: 5px;
                font-size: 16px;
                font-weight: bold;
                border: none;
            }
            QPushButton:hover {
                background-color: #c82333;
            }
        """)
        self.delete_button.clicked.connect(self.delete_note)
        self.button_layout.addWidget(self.delete_button)

        # View Note Button
        self.view_button = QPushButton(qta.icon('fa.eye', color='white'), "View Note", self)
        self.view_button.setStyleSheet("""
            QPushButton {
                background-color: #007bff;
                color: white;
                padding: 12px 20px;
                border-radius: 5px;
                font-size: 16px;
                font-weight: bold;
                border: none;
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
        """)
        self.view_button.clicked.connect(self.view_note)
        self.button_layout.addWidget(self.view_button)

        self.layout.addLayout(self.button_layout)

        # Set the layout for the window
        self.setLayout(self.layout)

    def get_backend_url(self):
        # 获取用户输入的 URL
        url = self.url_input.text().strip()
        if not url:
            QMessageBox.warning(self, "URL Error", "Please enter a valid Flask API URL.")
            return None
        return url

    def create_note(self):
        url = self.get_backend_url()
        if not url:
            return

        name = self.name_input.text()
        password = self.password_input.text()
        content = self.content_input.toPlainText()

        if not name or not password or not content:
            QMessageBox.warning(self, "Input Error", "Please fill in all fields.")
            return

        # 发起 POST 请求到 Flask 后端创建笔记
        response = requests.post(f'{url}/create_note', json={'name': name, 'password': password, 'content': content})

        if response.status_code == 201:
            QMessageBox.information(self, "Success", "Note created successfully!")
        else:
            QMessageBox.warning(self, "Error", response.json().get('error', 'Unknown error'))

    def delete_note(self):
        url = self.get_backend_url()
        if not url:
            return

        name = self.name_input.text()

        if not name:
            QMessageBox.warning(self, "Input Error", "Please provide the note name.")
            return

        # 发起 DELETE 请求到 Flask 后端删除笔记
        response = requests.delete(f'{url}/delete_note', json={'name': name})

        if response.status_code == 200:
            QMessageBox.information(self, "Success", "Note deleted successfully!")
        else:
            QMessageBox.warning(self, "Error", response.json().get('error', 'Unknown error'))

    def view_note(self):
        url = self.get_backend_url()
        if not url:
            return

        name = self.name_input.text()

        if not name:
            QMessageBox.warning(self, "Input Error", "Please provide the note name.")
            return

        # 发起 GET 请求到 Flask 后端查看笔记
        response = requests.get(f'{url}/view_note', params={'name': name})

        if response.status_code == 200:
            self.content_input.setPlainText(response.json()['content'])
        else:
            QMessageBox.warning(self, "Error", response.json().get('error', 'Unknown error'))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = NoteApp()
    window.show()
    sys.exit(app.exec_())
